const router = require("koa-router")();
const moment = require("moment");
const uuid = require("uuid/v1");
const path = require("path");
const Jimp = require("jimp");
const fse = require("fs-extra");

/**
 *
 * api {get} /home/user 获取账号基本信息
 *
 */
router.get("/user", async (ctx, nex) => {
  const user = ctx.user;
  // 查询用户手机号
  const result = await BaaS.Models.user
    .query(qb => {
      qb.where("id", "=", user.id);
    })
    .fetch({
      withRelated: ["user_info.avater", "user_type"]
    });
  const avaterUrl = result.user_info.avater_id
    ? result.user_info.avater.savename
    : "";
  if (avaterUrl) {
    Object.assign(result.user_info.avater, {
      url: ctx.config("qiniu.host") + avaterUrl
    });
  }

  if (result) {
    ctx.success(result);
  } else {
    ctx.error("暂无信息");
  }
});
/**
 * api {post} /home/user 提交账号基本信息
 *
 * apiParam {String} phone 账号
 * apiParam {String} nickname 昵称
 * apiParam {Number} qq_num qq号
 * apiParam {Number} avater_id 头像图片id
 * apiParam {String} sign 签名
 *
 */
router.post("/user", async (ctx, nex) => {
  const user = ctx.user;
  const avaterId = ctx.post.avater_id;
  const qqNum = ctx.post.qq_num;
  const { id, nickname, sign = "" } = ctx.post;
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty({ nickname: nickname, avaterId: avaterId }, [
    "nickname",
    "avaterId"
  ]);
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  const key = `nickname:${nickname}:avater_id:${avaterId}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    await BaaS.Models.user_info
      .forge({
        id: id,
        user_id: user.id,
        nickname: nickname,
        avater_id: avaterId,
        qq_num: qqNum,
        sign: sign
      })
      .save();
    ctx.success("保存成功");
    // 解锁
    await BaaS.redis.unlock(key);
  } else {
    console.log(`${key} Waiting`);
  }
});

/**
 *
 * api {get} /home/authenticate 获取账号认证信息
 *
 */
router.get("/authenticate", async (ctx, nex) => {
  const user = ctx.user;
  const result = await BaaS.Models.company
    .query(qb => {
      qb.where("user_id", "=", user.id);
    })
    .fetch({
      withRelated: ["image"]
    });
  const licenseImg = result.image
    ? ctx.config("qiniu.host") + result.image.savename
    : "";
  if (licenseImg) {
    Object.assign(result.image, {
      url: licenseImg
    });
  }
  if (result) {
    ctx.success(result);
  } else {
    ctx.error("暂无信息");
  }
});
/**
 *
 * api {post} /home/authenticate 账号认证信息
 *
 * apiParam {String} name 企业名称
 * apiParam {String} creditNum 信用代码
 * apiParam {Number} licenseId 执照照片id
 *
 */
router.post("/authenticate", async (ctx, nex) => {
  const user = ctx.user;
  const { name, creditNum, licenseId } = ctx.post;
  if (!name || !creditNum || !licenseId) {
    ctx.error("字段不正确");
    return;
  }
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty(
    { name: name, creditNum: creditNum, licenseId: licenseId },
    ["name", "creditNum", "licenseId"]
  );
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  // 验证信用代码
  // const regExp = /^[1-9A-GY]{1}[1239]{1}[1-5]{1}[0-9]{5}[0-9A-Z]{10}$/gi;
  // if (!regExp.test(creditNum)) {
  //   ctx.error("信用代码表达式格式不正确");
  //   return;
  // }
  // 企业信息
  const companyInfo = await BaaS.Models.company
    .query(qb => {
      qb.where("user_id", "=", user.id);
    })
    .fetch();

  const key = `user_id:${
    user.id
  }:name${name}:creditNum${creditNum}:licenseId${licenseId}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    await BaaS.Models.company
      .forge({
        id: companyInfo.id,
        user_id: user.id,
        company_name: name,
        credit_num: creditNum,
        license_id: licenseId
      })
      .save();
    ctx.success("保存成功");
    // 解锁
    await BaaS.redis.unlock(key);
  } else {
    console.log(`${key} Waiting`);
  }
});
/**
 * api {post} /home/image/upload 用户上传头像
 *
 * apiHeader {String} Token Token
 * apiParam {File} file 图片
 *
 */
router.post("/image/upload", async (ctx, nex) => {
  const user = ctx.user;
  if (!ctx.file && !ctx.file.file) {
    throw new Error("Upload Image Error");
  }
  const file = ctx.file.file;
  // 后缀名
  let ext = "";
  switch (file.type) {
    case "image/jpg":
      ext = "jpg";
      break;
    case "image/pjpeg":
      ext = "jpg";
      break;
    case "image/jpeg":
      ext = "jpg";
      break;
    case "image/png":
      ext = "png";
      break;
    case "image/x-png":
      ext = "png";
      break;
  }
  if (!ext) {
    await fse.remove(file.path);
    return;
  }
  const savepath = moment().format("YYYY-MM-DD");
  const savename = uuid() + "." + ext;
  addData = {
    user_id: user.id,
    name: file.name,
    ext: ext,
    type: file.type,
    savename: savename,
    size: file.size,
    savepath: savepath
  };
  const key = `name:${file.name}:type:${file.type}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    // 存数据库
    const avater = await BaaS.Models.user_image.forge(addData).save();

    const imageUrl = await ctx.uploadFile(file.path, savename);
    ctx.success(
      {
        url: `${imageUrl}`,
        avater_id: avater.id
      },
      "success"
    );
    // 解锁
    await BaaS.redis.unlock(key);
  } else {
    console.log(`${key} Waiting`);
  }
});

module.exports = router;
